package com.xiaogao.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaogao.autofill.annotation.FillUserInfo;
import com.xiaogao.common.utils.BeanListUtils;
import com.xiaogao.sys.mapper.SysDictDataMapper;
import com.xiaogao.sys.model.SysDictData;
import com.xiaogao.sys.request.dict.data.AddParam;
import com.xiaogao.sys.request.dict.data.UpdateParam;
import com.xiaogao.sys.response.SysDictDataResponse;
import com.xiaogao.sys.service.SysDictDataService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@RequiredArgsConstructor
@Service
@Slf4j
public class SysDictDataServiceImpl extends ServiceImpl<SysDictDataMapper, SysDictData> implements SysDictDataService {
    private final SysDictDataMapper sysDictDataMapper;

    @Override
    public void delete(List<String> ids) {
        if (!CollectionUtils.isEmpty(ids)) {
            sysDictDataMapper.deleteByIds(ids);
        }
    }

    @Override
    public void add(AddParam addParam) {
        // check unique  -->  type  value
        LambdaQueryWrapper<SysDictData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDictData::getType,addParam.getType());
        wrapper.eq(SysDictData::getValue,addParam.getValue());
        SysDictData dbSysDictData = sysDictDataMapper.selectOne(wrapper);
        if(dbSysDictData == null){
            SysDictData sysDictData = new SysDictData();
            BeanUtils.copyProperties(addParam,sysDictData);
            sysDictDataMapper.insert(sysDictData);
        }else{
            BeanUtils.copyProperties(addParam,dbSysDictData);
//            dbSysDictData.setKey(addParam.getKey());
//            dbSysDictData.setValue(addParam.getValue());
//            dbSysDictData.setSort(addParam.getSort());
//            dbSysDictData.setCss(addParam.getCss());
//            dbSysDictData.setType(addParam.getType());
            sysDictDataMapper.updateById(dbSysDictData);
        }
    }

    @Override
    public void update(UpdateParam updateParam) {
        SysDictData sysDictData = new SysDictData();
        BeanUtils.copyProperties(updateParam,sysDictData);
        sysDictDataMapper.updateById(sysDictData);
    }

    @FillUserInfo
    @Override
    public List<SysDictDataResponse> querySelective(String type) {
        LambdaQueryWrapper<SysDictData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDictData::getType,type);
        wrapper.orderByAsc(SysDictData::getSort);
        List<SysDictData> sysDictDataList = sysDictDataMapper.selectList(wrapper);
        return BeanListUtils.copyList(sysDictDataList, SysDictDataResponse.class);
    }
}
